/*
 * MegaMek - Copyright (C) 2000,2001,2002,2003,2004 Ben Mazur (bmazur@sev.org)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 */

/*
 * ChargeAttackAction.java
 *
 * Created on March 12, 2002, 3:23 PM
 */

package megamek.common.actions;

import java.util.Enumeration;

import megamek.common.Building;
import megamek.common.Compute;
import megamek.common.Coords;
import megamek.common.CriticalSlot;
import megamek.common.Entity;
import megamek.common.EntityWeightClass;
import megamek.common.GunEmplacement;
import megamek.common.IEntityMovementType;
import megamek.common.IGame;
import megamek.common.IHex;
import megamek.common.ILocationExposureStatus;
import megamek.common.Infantry;
import megamek.common.Mech;
import megamek.common.MovePath;
import megamek.common.MoveStep;
import megamek.common.Player;
import megamek.common.Protomech;
import megamek.common.TargetRoll;
import megamek.common.Targetable;
import megamek.common.Terrains;
import megamek.common.ToHitData;



/**
 * Represents one unit charging another. Stores information about where the
 * target is supposed to be for the charge to be successful, as well as normal
 * attack info.
 *
 * @author Ben Mazur
 */
public class ChargeAttackAction extends DisplacementAttackAction {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -3549351664290057785L;

    /**
     * Instantiates a new charge attack action.
     *
     * @param attacker the attacker
     * @param target the target
     */
    public ChargeAttackAction(Entity attacker, Targetable target) {
        this(attacker.getId(), target.getTargetType(), target.getTargetId(), target.getPosition());
    }

    /**
     * Instantiates a new charge attack action.
     *
     * @param entityId the entity id
     * @param targetType the target type
     * @param targetId the target id
     * @param targetPos the target pos
     */
    public ChargeAttackAction(int entityId, int targetType, int targetId, Coords targetPos) {
        super(entityId, targetType, targetId, targetPos);
    }

    /**
     * To-hit number for a charge, assuming that movement has been handled.
     *
     * @param game the game
     * @return the to hit data
     */
    public ToHitData toHit(IGame game) {
        return toHit(game, false);
    }

    /**
     * To hit.
     *
     * @param game the game
     * @param skid the skid
     * @return the to hit data
     */
    public ToHitData toHit(IGame game, boolean skid) {
        final Entity entity = game.getEntity(getEntityId());
        return toHit(game, game.getTarget(getTargetType(), getTargetId()), entity.getPosition(), entity.getElevation(), entity.moved, skid, false);
    }

    /**
     * To-hit number for a charge, assuming that movement has been handled.
     *
     * @param game the game
     * @param target the target
     * @param src the src
     * @param elevation the elevation
     * @param movement the movement
     * @param skid the skid
     * @param gotUp the got up
     * @return the to hit data
     */
    public ToHitData toHit(IGame game, Targetable target, Coords src, int elevation, int movement, boolean skid, boolean gotUp) {
        final Entity entity = getEntity(game);

        // arguments legal?
        ensureEntityNotNull(entity);

        // Due to pretreatment of physical attacks, the target may be null.
        if (target == null) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is null");
        }

        int targetId = Entity.NONE;
        Entity tEntity = null;
        if (target.getTargetType() == Targetable.TYPE_ENTITY) {
            tEntity = (Entity) target;
            targetId = target.getTargetId();
        }

        if (!game.getOptions().booleanOption("friendly_fire")) {
            // a friendly unit can never be the target of a direct attack.
            int teamOwner = entity.getOwner().getTeam();
			if (!skid && (target.getTargetType() == Targetable.TYPE_ENTITY)
                    && ((((Entity)target).getOwnerId() == entity.getOwnerId())
                            || ((((Entity)target).getOwner().getTeam() != Player.TEAM_NONE)
                                    && (teamOwner != Player.TEAM_NONE)
                                    && (teamOwner == ((Entity)target).getOwner().getTeam())))) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "A friendly unit can never be the target of a direct attack.");
            }
        }

        IHex attHex = game.getBoard().getHex(src);
        IHex targHex = game.getBoard().getHex(target.getPosition());
        final int attackerElevation = elevation + attHex.getElevation();
        final int attackerHeight = attackerElevation + entity.height();
        final int targetElevation = target.getElevation() + targHex.getElevation();
        final int targetHeight = targetElevation + target.getHeight();
        Building bldg = game.getBoard().getBuildingAt(getTargetPos());
        ToHitData toHit = null;
        boolean targIsBuilding = ((getTargetType() == Targetable.TYPE_FUEL_TANK) || (getTargetType() == Targetable.TYPE_BUILDING));

        boolean inSameBuilding = Compute.isInSameBuilding(game, entity, tEntity);

        // can't target yourself
        if (entity.equals(tEntity)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "You can't target yourself");
        }

        // Can't target a transported entity.
        if ((tEntity != null) && (Entity.NONE != tEntity.getTransportId())) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is a passenger.");
        }

        // Can't target a entity conducting a swarm attack.
        if ((tEntity != null) && (Entity.NONE != tEntity.getSwarmTargetId())) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is swarming a Mek.");
        }

        // check range
        if (src.distance(target.getPosition()) > 1) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target not in range");
        }

        // mechs can only charge standing mechs
        if ((entity instanceof Mech) && !skid) {
            if ((tEntity != null) && !(tEntity instanceof Mech)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is not a mech");
            }
            if ((tEntity != null) && tEntity.isProne()) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is prone");
            }
        } else if (tEntity instanceof Infantry) {
            // Can't charge infantry.
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is infantry");
        } else if (tEntity instanceof Protomech) {
            // Can't charge protomechs.
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is protomech");
        }

        // target must be within 1 elevation level
        if ((attackerElevation > targetHeight) || (attackerHeight < targetElevation)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target must be within 1 elevation level");
        }

        // can't attack mech making a different displacement attack
        if ((tEntity != null) && tEntity.hasDisplacementAttack()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is already making a charge/DFA attack");
        }

        // target must have moved already, unless it's a skid charge
        if ((tEntity != null) && !tEntity.isDone() && !skid) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target must be done with movement");
        }

        // can't attack the target of another displacement attack
        if ((tEntity != null) && tEntity.isTargetOfDisplacementAttack() && (tEntity.findTargetedDisplacement().getEntityId() != entity.getId())) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is the target of another charge/DFA");
        }

        // Can't target units in buildings (from the outside).
        if ((null != bldg) && (!targIsBuilding) && (tEntity != null) && Compute.isInBuilding(game, tEntity)) {
            if (!Compute.isInBuilding(game, entity)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is inside building");
            } else if (!game.getBoard().getBuildingAt(entity.getPosition()).equals(bldg)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is inside differnt building");
            }
        }

        // Attacks against adjacent buildings automatically hit.
        if ((target.getTargetType() == Targetable.TYPE_BUILDING) || (target.getTargetType() == Targetable.TYPE_FUEL_TANK) || (target instanceof GunEmplacement)) {
            return new ToHitData(TargetRoll.AUTOMATIC_SUCCESS, "Targeting adjacent building.");
        }

        // Can't target woods or ignite a building with a physical.
        if ((target.getTargetType() == Targetable.TYPE_BLDG_IGNITE) || (target.getTargetType() == Targetable.TYPE_HEX_CLEAR) || (target.getTargetType() == Targetable.TYPE_HEX_IGNITE)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Invalid attack");
        }

        // Set the base BTH
        int base = entity.getCrew().getPiloting();

        toHit = new ToHitData(base, "base");

        appendToHit(game, movement, entity, targetId, tEntity, toHit,
				inSameBuilding);

        // attacker is spotting
        checkSpottingAttacker(entity, toHit);

        if (tEntity != null) {
            // piloting skill differential
            testPiloting(entity, tEntity, toHit);

            // target prone
            targetProneCheck(tEntity, toHit);

            // water partial cover?
            waterCoveredCheck(tEntity, targHex, toHit);
        }

        // If it has a torso-mounted cockpit and two head sensor hits or three
        // sensor hits...
        // It gets a =4 penalty for being blind!
        if ((entity instanceof Mech) && (((Mech) entity).getCockpitType() == Mech.COCKPIT_TORSO_MOUNTED)) {
            int sensorHits = entity.getBadCriticals(CriticalSlot.TYPE_SYSTEM, Mech.SYSTEM_SENSORS, Mech.LOC_HEAD);
            int sensorHits2 = entity.getBadCriticals(CriticalSlot.TYPE_SYSTEM, Mech.SYSTEM_SENSORS, Mech.LOC_CT);
            if ((sensorHits + sensorHits2) == 3) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Sensors Completely Destroyed for Torso-Mounted Cockpit");
            } else if (sensorHits == 2) {
                toHit.addModifier(4, "Head Sensors Destroyed for Torso-Mounted Cockpit");
            }
        }

        // target immobile
        toHit.append(Compute.getImmobileMod(tEntity));

        // skids have a penalty for unintentional charge
        checkIfSkid(skid, toHit);

        Compute.modifyPhysicalBTHForAdvantages(entity, tEntity, toHit, game);

        //evading bonuses (
        if(tEntity.isEvading()) {
            toHit.addModifier(tEntity.getEvasionBonus(), "target is evading");
        }

        // determine hit direction
        toHit.setSideTable(tEntity.sideTable(src));

        // all charges resolved against full-body table, except vehicles
        // and charges against mechs in water partial cover
        setToHitbasedifWater(target, entity, tEntity, targHex, toHit);

        //Attacking Weight Class Modifier.
        checkWeightClassModifier(game, entity, toHit);

        addToHitIndustrialTSM(entity, toHit);

        // done!
        return toHit;
    }

	/**
	 * @param entity
	 * @param toHit
	 */
	public void addToHitIndustrialTSM(final Entity entity, ToHitData toHit) {
		if ((entity instanceof Mech) && ((Mech)entity).hasIndustrialTSM()) {
            toHit.addModifier(2, "industrial TSM");
        }
	}

	/**
	 * @param entity
	 * @param toHit
	 */
	public void checkSpottingAttacker(final Entity entity, ToHitData toHit) {
		if (entity.isSpotting()) {
            toHit.addModifier(+1, "attacker is spotting");
        }
	}

	/**
	 * @param game
	 * @param movement
	 * @param entity
	 * @param targetId
	 * @param tEntity
	 * @param toHit
	 * @param inSameBuilding
	 */
	public void appendToHit(IGame game, int movement, final Entity entity,
			int targetId, Entity tEntity, ToHitData toHit,
			boolean inSameBuilding) {
		// attacker movement
        toHit.append(Compute.getAttackerMovementModifier(game, entity.getId(), movement));

        // target movement
        toHit.append(Compute.getTargetMovementModifier(game, targetId));

        // attacker terrain
        toHit.append(Compute.getAttackerTerrainModifier(game, entity.getId()));

        // target terrain
        toHit.append(Compute.getTargetTerrainModifier(game, tEntity, 0, inSameBuilding));
	}

	/**
	 * @param entity
	 */
	public void ensureEntityNotNull(final Entity entity) {
		if (entity == null) {
            throw new IllegalStateException("Attacker is null");
        }
	}

	/**
	 * @param entity
	 * @param tEntity
	 * @param toHit
	 */
	public void testPiloting(final Entity entity, Entity tEntity,
			ToHitData toHit) {
		if (entity.getCrew().getPiloting() != tEntity.getCrew().getPiloting()) {
		    toHit.addModifier(entity.getCrew().getPiloting() - tEntity.getCrew().getPiloting(), "piloting skill differential");
		}
	}

	/**
	 * @param tEntity
	 * @param targHex
	 * @param toHit
	 */
	public void waterCoveredCheck(Entity tEntity, IHex targHex, ToHitData toHit) {
		if ((tEntity.height() > 0) && (tEntity.getElevation() == -1) && (targHex.terrainLevel(Terrains.WATER) == tEntity.height())) {
		    toHit.addModifier(1, "target has partial cover");
		}
	}

	/**
	 * @param tEntity
	 * @param toHit
	 */
	public void targetProneCheck(Entity tEntity, ToHitData toHit) {
		if (tEntity.isProne()) {
		    toHit.addModifier(-2, "target prone and adjacent");
		}
	}

	/**
	 * @param skid
	 * @param toHit
	 */
	public void checkIfSkid(boolean skid, ToHitData toHit) {
		if (skid) {
            toHit.addModifier(3, "unintentional charge");
        }
	}

	/**
	 * @param target
	 * @param entity
	 * @param tEntity
	 * @param targHex
	 * @param toHit
	 */
	public void setToHitbasedifWater(Targetable target, final Entity entity,
			Entity tEntity, IHex targHex, ToHitData toHit) {
		if ((targHex.terrainLevel(Terrains.WATER) == tEntity.height()) && (tEntity.getElevation() == -1) && (tEntity.height() > 0)) {
            toHit.setHitTable(ToHitData.HIT_PUNCH);
        } else if (entity.getHeight() < target.getHeight()) {
            toHit.setHitTable(ToHitData.HIT_KICK);
        } else {
            toHit.setHitTable(ToHitData.HIT_NORMAL);
        }
	}

	/**
	 * @param game
	 * @param entity
	 * @param toHit
	 */
	public void checkWeightClassModifier(IGame game, final Entity entity,
			ToHitData toHit) {
		if ( game.getOptions().booleanOption("tacops_attack_physical_psr") ) {
            if ( entity.getWeightClass() == EntityWeightClass.WEIGHT_LIGHT ) {
                toHit.addModifier(-2, "Weight Class Attack Modifier");
            }else if ( entity.getWeightClass() == EntityWeightClass.WEIGHT_MEDIUM ) {
                toHit.addModifier(-1, "Weight Class Attack Modifier");
            }
        }
	}

    /**
     * Checks if a charge can hit the target, taking account of movement.
     *
     * @param game the game
     * @param movePath the md
     * @return the to hit data
     */
    public ToHitData toHit(IGame game, MovePath movePath) {
        final Entity entity = game.getEntity(getEntityId());
        final Targetable target = getTarget(game);
        Coords chargeSrc = entity.getPosition();
        int chargeEl = entity.getElevation();
        MoveStep chargeStep = null;

        // let's just check this
        if (!movePath.contains(MovePath.STEP_CHARGE)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Charge action not found in movment path");
        }

        // no jumping
        if (movePath.contains(MovePath.STEP_START_JUMP)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "No jumping allowed while charging");
        }

        // no backwards
        if (movePath.contains(MovePath.STEP_BACKWARDS) || movePath.contains(MovePath.STEP_LATERAL_LEFT_BACKWARDS) || movePath.contains(MovePath.STEP_LATERAL_RIGHT_BACKWARDS)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "No backwards movement allowed while charging");
        }

        //no evading
        if(movePath.contains(MovePath.STEP_EVADE)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "No evading while charging");
        }

        // determine last valid step
        movePath.compile(game, entity);
        for (final Enumeration<MoveStep> i = movePath.getSteps(); i.hasMoreElements();) {
            final MoveStep step = i.nextElement();
            if (step.getMovementType() == IEntityMovementType.MOVE_ILLEGAL) {
                break;
            }
            if (step.getType() == MovePath.STEP_CHARGE) {
                chargeStep = step;
            } else {
                chargeSrc = step.getPosition();
                chargeEl = step.getElevation();
            }
        }

        // need to reach target
        if ((chargeStep == null) || !target.getPosition().equals(chargeStep.getPosition())) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Could not reach target with movement");
        }
        if (!movePath.getSecondLastStep().isLegalEndPos()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Violation of stacking limit in second last step");
        }

        return toHit(game, target, chargeSrc, chargeEl, chargeStep.getMovementType(), false, movePath.contains(MovePath.STEP_GET_UP) || movePath.contains(MovePath.STEP_CAREFUL_STAND));
    }

    /**
     * Damage that a mech does with a successful charge. Assumes that
     * delta_distance is correct.
     *
     * @param entity the entity
     * @return the damage for
     */
    public static int getDamageFor(Entity entity) {
        return getDamageFor(entity, entity, false, 0, entity.delta_distance);
    }

    /**
     * Gets the damage for.
     *
     * @param entity the entity
     * @param tacops the tacops
     * @param hexesMoved the hexes moved
     * @return the damage for
     */
    public static int getDamageFor(Entity entity, boolean tacops, int hexesMoved) {
        return getDamageFor(entity, entity, tacops, 0, hexesMoved);
    }

    /**
     * Gets the damage for.
     *
     * @param entity the entity
     * @param target the target
     * @param tacops the tacops
     * @param mos the mos
     * @return the damage for
     */
    public static int getDamageFor(Entity entity, Entity target, boolean tacops, int mos) {
        return getDamageFor(entity, target, tacops, mos , entity.delta_distance);
    }

    /**
     * Gets the damage for.
     *
     * @param entity the entity
     * @param target the target
     * @param tacops the tacops
     * @param mos the mos
     * @param hexesMoved1 the hexes moved1
     * @return the damage for
     */
    public static int getDamageFor(Entity entity, Entity target, boolean tacops, int mos, int hexesMoved1) {
    	int hexesMoved = hexesMoved1;
        if ( !tacops ) {
            if (hexesMoved == 0) {
                hexesMoved = 1;
            }
            return (int) Math.ceil((entity.getWeight() / 10.0) * (hexesMoved - 1) * (entity.getLocationStatus(1) == ILocationExposureStatus.WET ? 0.5 : 1));
        }
        return (int) Math.floor((((target.getWeight() * entity.getWeight()) * hexesMoved) / (target.getWeight() + entity.getWeight())) / 10+mos);
    }

    /**
     * Damage that a mech suffers after a successful charge.
     *
     * @param entity the entity
     * @param bldg the bldg
     * @param coords the coords
     * @return the damage taken by
     */
    public static int getDamageTakenBy(Entity entity, Building bldg, Coords coords) {
        // ASSUMPTION: 10% of buildings CF at start of phase, round up.
        return (int) Math.ceil(bldg.getPhaseCF(coords) / 10.0);
    }

    /**
     * Gets the damage taken by.
     *
     * @param entity the entity
     * @param target the target
     * @return the damage taken by
     */
    public static int getDamageTakenBy(Entity entity, Entity target) {
        return getDamageTakenBy(entity, target, false, 0);
    }

    /**
     * Gets the damage taken by.
     *
     * @param entity the entity
     * @param target the target
     * @param tacops the tacops
     * @return the damage taken by
     */
    public static int getDamageTakenBy(Entity entity, Entity target, boolean tacops) {
        return getDamageTakenBy(entity, target, tacops, entity.delta_distance);
    }

    /**
     * Gets the damage taken by.
     *
     * @param entity the entity
     * @param target the target
     * @param tacops the tacops
     * @param distance the distance
     * @return the damage taken by
     */
    public static int getDamageTakenBy(Entity entity, Entity target, boolean tacops, int distance) {
        if (!tacops) {
            return (int) Math.ceil(target.getWeight() / 10.0 * (entity.getLocationStatus(1) == ILocationExposureStatus.WET ? 0.5 : 1));
        } else {
            return (int) Math.floor((((target.getWeight() * entity.getWeight()) * distance) / (target.getWeight() + entity.getWeight())) / 10);
        }
    }

}
